<script src='${rc.getContextPath()}/manage/js/fullcalendar/lang/${lan}.js'></script>
<link href='${rc.getContextPath()}/manage/js/fullcalendar/fullcalendar.css?v=${ver}' rel='stylesheet' />
<link href='${rc.getContextPath()}/manage/js/fullcalendar/fullcalendar.print.css?v=${ver}' rel='stylesheet' media='print' />
<link rel='stylesheet' href='${rc.getContextPath()}/manage/styles/colorPicker/spectrum.css' />
<style>
.cal {
    margin: 0 auto;
    width: 100%;
    height: 300px;
}

.cal .fc-event {
    width: 100px;
    background: none;
    border: none;
}

.cal .fc-today {
    background: none;
}

.cal .fc-event .fc-content .fc-title {
    color: #666;
}

.fancy {
    width: 450px;
    height: auto
}

.fancy h3 {
    height: 30px;
    line-height: 30px;
    border-bottom: 1px solid #d3d3d3;
    font-size: 14px
}

.fancy form {
    padding: 10px
}

.fancy p {
    height: 28px;
    line-height: 28px;
    padding: 4px;
    color: #999
}

.input {
    height: 20px;
    line-height: 20px;
    padding: 2px;
    border: 1px solid #d3d3d3;
    width: 100px
}

.btn {
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    padding: 5px 12px;
    cursor: pointer
}

.btn_ok {
    background: #360;
    border: 1px solid #390;
    color: #fff
}

.btn_cancel {
    background: #f0f0f0;
    border: 1px solid #d3d3d3;
    color: #666
}

.btn_del {
    background: #f90;
    border: 1px solid #f80;
    color: #fff
}

.sub_btn {
    height: 32px;
    line-height: 32px;
    padding-top: 6px;
    border-top: 1px solid #f0f0f0;
    text-align: right;
    position: relative
}

.sub_btn .del {
    position: absolute;
    left: 2px
}

.fancy label {
    float: left;
    width: 100px;
    line-height: 23px;
    text-align: left;
}
.cal .fc-title {
    font-size: 14px;
}

#apply .panel .panelHeader
{
height:30px;
}
</style>


<form method="post" action="${rc.getContextPath()}/manage/calendar/saveCalendar" class=" pageForm required-validate" onsubmit="return calendarJs._tsubmit(this);">
    <div class="pageContent">
        <div class="pageFormContent">
            <fieldset>
                <input type="hidden" id="calendarDaysStr" name="calendarDaysStr"> 
                <input type="hidden" name="navTabId" value="${navTabId!''}"> <input type="hidden" name="id" value="<#if (calendar.calendarCode)??>${calendar.calendarCode!''}</#if>">
                <dl>

                    <dt><@label key="calendarCode.C,colon">日历编号：</@label></dt>
                    <dd>
                        <input class="required  alphanumeric toUp" name="calendarCode" value="<#if (calendar.calendarCode)??>${calendar.calendarCode!''}</#if>" type="text" maxlength="20" remote="${rc.getContextPath()}/manage/calendar/validateCalendar" warn="<@label key="calendarCodeExist.M">日历编号已经存在</@label>"/>
                    </dd>
                </dl>
                <dl>
                    <dt><@label key="calendarText.C,colon">日历描述：</@label></dt>
                    <dd>
                        <input class="required" name="calendarText" value="<#if (calendar.calendarText)??>${calendar.calendarText!''}</#if>" type="text" maxlength="60" />
                    </dd>
                </dl>

                <dl>
                    <dt><@label key="defaultCalendarPattern.C,colon">默认日历模式：</@label></dt>
                    <dd>
                        <select style="width: 147px;" name="calendarPatternCode">
                            <option value=""></option> <#if calendarPatterns??><#if calendarPatterns?size>0><#list calendarPatterns as calendarPattern>
                            <option value="${calendarPattern.calendarPatternCode!''}">${calendarPattern.calendarPatternCode!''}-${calendarPattern.calendarPatternText!''}</option> </#list></#if></#if>
                        </select>
                    </dd>
                </dl>
                <dl class="nowrap">
                    <dd>
                        <div id='calCalendar' class="cal"></div>
                    </dd>
                </dl>
                <dl class="nowrap" id="apply">
                <div class="panel" currentIndex="0" eventType="click" style="width: 100%; margin: 0;">
                    <h1 style="line-height:32px"><@label key="applyCalendar.C">应用日历模式</@label></h1>
                    <div>
                    <dl style="width:260px;clear: none;">
                    <dt><@label key="dateRange.C,colon">日期范围：</@label></dt>
                    <dd>
                        <input type="text" class="date"  id="minDate" name="minDate" readonly max_date="{maxDate}" /><a class="inputDateButton" href="javascript:;"><@label key='select.B'>选择</@label></a>
                    </dd>
                </dl>
                <dl style="width:170px;clear: none;">
                <dt style="width:8px">-</dt>
                <dd>
                <input type="text" class="date"  id="maxDate" name="maxDate" readonly min_date="{minDate}" /><a class="inputDateButton" href="javascript:;"><@label key='select.B'>选择</@label></a>
                </dd>
                </dl>
                <dl style="width:430px;clear: none;">
                    <dt><@label key="calendarPattern.C,colon">日历模式：</@label></dt>
                    <dd>
                        <select style="width: 147px;" id="applyPattern">
                            <#if calendarPatterns??><#if calendarPatterns?size>0>
                            <#list calendarPatterns as calendarPattern>
                            <option baseDate="${calendarPattern.baseDate?string('yyyy-MM-dd')}" items='${calendarPattern.itemsStr!''}' value="${calendarPattern.calendarPatternCode!''}">${calendarPattern.calendarPatternCode!''}-${calendarPattern.calendarPatternText!''}</option> 
                            </#list></#if></#if>
                        </select>
                            <label style="margin-left: 10px;width: 82px;"><input type="checkbox" id="coverFlag" name="coverFlag" value="1"><@label key="coverFlag.C">覆盖旧数据</@label></label>
                            <div class="buttonActive" id="save">
                            <div class="buttonContent">
                            <button type="button" onclick="calendarJs._apply()"><@label key="apply.B">应用</@label></button>
                           </div>
                           </div>
                    </dd>
                </dl>
                    </div>
                </div>
                </dl>
            </fieldset>
        </div>
        <div class="formBar">
            <ul>
                <li><div class="buttonActive" id="save">
                        <div class="buttonContent">
                            <button type="submit"><@label key="save.B">保存</@label></button>
                        </div>
                    </div></li>
                <li>
                    <div class="buttonActiveGrey">
                        <div class="buttonContent">
                            <button type="button" class="close"><@label key="cancel.B">取消</@label></button>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</form>

<div style="display:none">
<div id="openWindows">
    <input type="hidden" id="jsonIndex"> 
    <div class="pageContent">
        <div class="pageFormContent">
            <fieldset>
               <dl class="nowrap">
                    <dt><@label key="dayType.C">日类型</@label></dt>
                    <dd>
                        <select id="dayType">
                            <option value=''></option> <#list types as type>
                            <option value='${type.dayTypeCode}' text="${type.dayTypeText}" color="${type.displayColor}" >${type.dayTypeCode}-${type.dayTypeText}</option> </#list> 
                        </select>
                    </dd>
                </dl>
                <dl class="nowrap">
                    <dt><@label key="date.C,colon">日期：</@label></dt>
                    <dd>
                        <input id="selectDate" readOnly type="text" maxlength="60" />
                    </dd>
                </dl>
            </fieldset>
        </div>
        <div class="formBar" style="width:380px">
            <ul>
                <li><div class="buttonActive" id="save">
                        <div class="buttonContent">
                            <button type="button" onclick="calendarJs._dialogOk();"><@label key="ok.B">确定</@label></button>
                        </div>
                    </div></li>
                <li>
                    <div class="buttonActiveGrey">
                        <div class="buttonContent">
                            <button type="button" onclick="calendarJs._dialogClose();"><@label key="cancel.B">取消</@label></button>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</div>
</div>


<script type="text/javascript">
Date.prototype.Format = function (fmt) { //author: meizz   
    var o = {
        "M+": this.getMonth() + 1, //月份   
        "d+": this.getDate(), //日   
        "h+": this.getHours(), //小时   
        "m+": this.getMinutes(), //分   
        "s+": this.getSeconds(), //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds()
        //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
                .substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
                    : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var calendarJs = {
    currDialog:null,
    selectDay: "",
    selectText: "",
    calJson: [],
    _getCal: function () {
        return calendarJs.calJson;
    },
    _tsubmit: function (t) {
        $("#calendarDaysStr",calendarJs.currDialog).val(JSON.stringify(calendarJs.calJson));
        return validateCallback(t, dialogAjaxDone);
    },
    //日期加上天数得到新的日期  
    //dateTemp 需要参加计算的日期，days要添加的天数，返回新的日期，日期格式：YYYY-MM-DD  
    _getNewDay: function (dateTemp, days) {
        var dateTemp = dateTemp.split("-");
        var a=dateTemp[1] + '-' + dateTemp[2] + '-'
        + dateTemp[0];
        var nDate = new Date(dateTemp[0] + '-' + dateTemp[1] + '-'
                + dateTemp[2]);    
        var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);
           
        var rDate = new Date(millSeconds);
        var year = rDate.getFullYear();
        var month = rDate.getMonth() + 1;
        if (month < 10)
            month = "0" + month;
        var date = rDate.getDate();
        if (date < 10)
            date = "0" + date;
        return (year + "-" + month + "-" + date);
    },
    _dateDiff:function(sDate1, sDate2) {  //sDate1和sDate2是yyyy-MM-dd格式
         
        var aDate, oDate1, oDate2, iDays;
        aDate = sDate1.split("-");
        oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);  //转换为yyyy-MM-dd格式
        aDate = sDate2.split("-");
        oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
        iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
     
        return iDays;  //返回相差天数
    },
    _dialogOk: function () {
        var selectVal = $("#dayType", $.pdialog.getCurrent()).val();
        var index = $("#jsonIndex", $.pdialog.getCurrent()).val();
        calendarJs.selectText = $("#dayType option:selected",
                $.pdialog.getCurrent()).attr("text");
        var color=$("#dayType option:selected",
                $.pdialog.getCurrent()).attr("color");
        $.pdialog.close("editDay");
        if (index == "") {
            if (selectVal != "") {
                //新增
                var json = {};
                json.start = calendarJs.selectDay;
                json.title = calendarJs.selectText;
                json.type = selectVal;
                calendarJs.calJson.push(json);
                var backJson = {};
                backJson.start = calendarJs.selectDay;
                backJson.end=calendarJs.selectDay;
                backJson.rendering = 'background';
                backJson.color = color;
                calendarJs.calJson.push(backJson);
            }
        } else {
            if (selectVal != "") {
                //修改
                var backIndex = calendarJs._findBackEventIndex(calendarJs.calJson[index].start);
                calendarJs.calJson[index].title = calendarJs.selectText;
                calendarJs.calJson[index].type = selectVal;
                calendarJs.calJson[backIndex].color = color;
            } else {
                //删除
                var backIndex = calendarJs._findBackEventIndex(calendarJs.calJson[index].start);
                calendarJs.calJson.splice(index, 1);
                calendarJs.calJson.splice(backIndex, 1);
                $('#calCalendar',calendarJs.currDialog).fullCalendar('removeEvents',
                        function (event) {
                            if (event.start.format() == calendarJs.selectDay && event.end == null) {
                                return true;
                            } else {
                                 if (event.start.format() == calendarJs.selectDay &&event.rendering != null&&event.end==null){
                                     return true;
                                 }
                                return false;
                            }

                        });
            }
        }
        $('#calCalendar',calendarJs.currDialog).fullCalendar( 'removeEventSource', calendarJs._getCal() );
        $('#calCalendar',calendarJs.currDialog).fullCalendar( 'addEventSource', calendarJs._getCal() );
    },
    _dialogClose: function () {
        $.pdialog.close("editDay");
    },
    _findEventIndex: function (data) {
        var index = null;
        $.each(calendarJs.calJson, function (n, value) {
            if (value.start == data && value.end == null&&value.rendering==null) {
                index = n;
            }
        });
        return index;
    },
    _findBackEventIndex: function (data) {
        var index = null;
        $.each(calendarJs.calJson, function (n, value) {
            if (value.start == data && value.end == data&&value.rendering!=null) {
                index = n;
            }
        });
        return index;
    },
    _dayClick:function(dateFmt)
    {
        var index = calendarJs._findEventIndex(dateFmt);
        if (index != null) {
            var $dialogClone = $("#openWindows",$.pdialog.getCurrent()).clone(true);
            $("#jsonIndex", $dialogClone).val(index);
            $("#selectDate", $dialogClone).val(dateFmt);
            var type = calendarJs.calJson[index].type;
            $("#dayType", $dialogClone).find("option[value=" + type+ "]").attr("selected", true);
            calendarJs.selectDay = dateFmt;
            $.pdialog.open('',"editDay","<@label key='editDay.C'>编辑工作日</@label>",{
                                mask : true,
                                width : 400,
                                height : 160,
                                maxable : false,
                                minable : false,
                                callback : function(dialogContent) {
                                    dialogContent.append($dialogClone);
                                }
                            });
        } else {
                var $dialogClone = $("#openWindows",$.pdialog.getCurrent()).clone(true);
                $("#jsonIndex", $dialogClone).val("");
                $("#selectDate", $dialogClone).val(dateFmt);
                $("#dayType", $dialogClone).val('');
                calendarJs.selectDay = dateFmt;

                $.pdialog.open('',"editDay","<@label key='editDay.C'>编辑工作日</@label>",{
                                    mask : true,
                                    width : 400,
                                    height : 160,
                                    maxable : false,
                                    minable : false,
                                    callback : function(dialogContent) {
                                        dialogContent.append($dialogClone);
                                    }
                                });
          }
    },
    _calDate:function(fromDay,pattern){
        var index = calendarJs._findEventIndex(fromDay);
        var backIndex = calendarJs._findBackEventIndex(fromDay);
        var coverFlag=false;
        if($("#coverFlag",calendarJs.currDialog).attr("checked")=="checked"){
            coverFlag=true;
        }
        if (index != null) {
            //已经存在工作日
            if(coverFlag){
                //需要覆盖
                if(pattern.dayTypeCode!=null){
                    //更新
                        calendarJs.calJson[index].title = pattern.dayTypeText;
                        calendarJs.calJson[index].type = pattern.dayTypeCode;
                        calendarJs.calJson[backIndex].color = pattern.displayColor;
                }else{
                    //删除
                     calendarJs.calJson.splice(index, 1);
                     calendarJs.calJson.splice(backIndex, 1);
                }
            }
        }
        else{
            //不存在工作日
            if(pattern.dayTypeCode!=null){
                var json = {};
                json.start = fromDay;
                json.title = pattern.dayTypeText;
                json.type = pattern.dayTypeCode;
                calendarJs.calJson.push(json);
                var backJson = {};
                backJson.start = fromDay;
                backJson.end=fromDay;
                backJson.rendering = 'background';
                backJson.color = pattern.displayColor;
                calendarJs.calJson.push(backJson);
            }
        }
    },
    _apply:function(){
        var now = new Date().formatDate("yyyy-MM-dd");
        var start=$("#minDate",calendarJs.currDialog).val();
        var end=$("#maxDate",calendarJs.currDialog).val();
        if(start==""||end==""){
             alertMsg.warn("<@label key='dateRangeNull.M'>请输入日期范围！</@label>");
        }
        else{
            if(start<now){
                alertMsg.warn("<@label key='dateRangeStartError.M'>开始时间不能小于今天！</@label>");
            }
            else if(end> calendarJs._getNewDay(now, 1000)){
                 alertMsg.warn("<@label key='dateRangeEndError.M'>结束时间需在当前日期的1000天内！</@label>");
            }
            else{
                var patternStr=$("#applyPattern option:selected",calendarJs.currDialog).attr("items");
                if(patternStr==null){
                     alertMsg.warn("<@label key='applyPatternError.M'>该日历模式不存在明细，请维护后使用！</@label>");
                }
                else{
                    $("#background,#progressBar",$("body")).show();
                    setTimeout(function(){
                        var pattern=eval(patternStr);
                        var baseDate=$("#applyPattern option:selected",calendarJs.currDialog).attr("baseDate");
                        var diff=calendarJs._dateDiff(start,baseDate);
                        if(start<baseDate)
                            {
                            diff++;
                            }
                        var totalDays=0;
                
                        for(var i=0;i<pattern.length;i++){  
                            totalDays+= pattern[i].days;
                            }  
                        var days=diff%totalDays;
                        var fromDay=start;
                        while(fromDay<=end)
                        {
                            for(var i=0;i<pattern.length;i++){  
                                
                                if(days>0){
                                    if(pattern[i].days<=days){
                                        days-=pattern[i].days;
                                        fromDay=calendarJs._getNewDay(fromDay, pattern[i].days-1);
                                    }
                                    else
                                    {
                                        var remainder=pattern[i].days-days;
                                        days=0;
                                        while(remainder>0){
                                            calendarJs._calDate(fromDay,pattern[i]);
                                            remainder--;
                                            fromDay=calendarJs._getNewDay(fromDay, 1);
                                            if(fromDay>end){
                                                break;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    var remainder=pattern[i].days;
                                    while(remainder>0){
                                        calendarJs._calDate(fromDay,pattern[i]);
                                        remainder--;
                                        fromDay=calendarJs._getNewDay(fromDay, 1)
                                        if(fromDay>end){
                                            break;
                                        }
                                    }
                                }
                                if(fromDay>end){
                                    break;
                                }
                            }  
                        }
                        $('#calCalendar',calendarJs.currDialog).fullCalendar( 'removeEventSource', calendarJs._getCal() );
                        $('#calCalendar',calendarJs.currDialog).fullCalendar( 'addEventSource', calendarJs._getCal() );
                        $("#background,#progressBar",$("body")).hide();
                        alertMsg.info("<@label key='applySuccess.M'>应用成功！</@label>");
                    },100);
                    
                }
            }
        }
        
    }
}

$(function () {
    calendarJs.currDialog=$.pdialog.getCurrent();
    var start = new Date().formatDate("yyyy-MM-dd");
    var end = calendarJs._getNewDay(start, 1000);
    var json = {};
    json.start = start;
    json.end = end;
    json.overlap = false;
    json.durationEditable = false;
    json.rendering = 'inverse-background';
    json.color = '#e6e6e6';
    calendarJs.calJson.push(json);
    $("#minDate",calendarJs.currDialog).val(start);
    $("#maxDate",calendarJs.currDialog).val(calendarJs._getNewDay(start, 30));
    var lastClickTime;
    var lastClickDay;
    $('#calCalendar',calendarJs.currDialog)
            .fullCalendar(
                    {
                        header: {
                            left: '',
                            center: 'prev,title,next,today',
                            right: ''
                        },
                        height: 300,
                        firstDay: 1,
                        selectable: true,
                        selectHelper: true,
                        unselectAuto: false,
                        editable: false,
                        eventLimit: true,
                        dayClick : function(date, jsEvent, view) {
                                //需要手动实现双击事件
                                var myDate = new Date();
                                //双击时才弹出新增
                                if (lastClickTime == null|| lastClickTime == '') {
                                    lastClickTime = myDate;
                                    lastClickDay = date;
                                } else {
                                    var ms = myDate - lastClickTime;
                                    if (date - lastClickDay == 0 && ms < 1000) {
                                        var dateFmt = date.format();
                                        if (dateFmt >= start&& dateFmt <= end) {
                                            calendarJs._dayClick(dateFmt);
                                        }
                                        //重新计算
                                        lastClickDay = "";
                                        lastClickTime = "";
                                    } else {
                                        //不满足双击事件
                                        lastClickDay = date;
                                        lastClickTime = myDate;
                                    }
                                }
                            },
                            eventClick : function(calEvent, jsEvent, view) {
                                $("#calCalendar",calendarJs.currDialog).fullCalendar('select', calEvent.start);
                                //需要手动实现双击事件
                                var myDate = new Date();
                                var currDay=calEvent.start.format().parseDate("yyyy-MM-dd");
                                //双击时才弹出新增
                                if (lastClickTime == null|| lastClickTime == '') {
                                    lastClickTime = myDate;
                                    lastClickDay = currDay;
                                } else {
                                    var ms = myDate - lastClickTime;
                                    if (currDay - lastClickDay == 0 && ms < 1000) {
                                        var dateFmt = calEvent.start.format();
                                        if (dateFmt >= start&& dateFmt <= end) {
                                            calendarJs._dayClick(dateFmt);
                                        }
                                        //重新计算
                                        lastClickDay = "";
                                        lastClickTime = "";
                                    } else {
                                        //不满足双击事件
                                        lastClickDay = currDay;
                                        lastClickTime = myDate;
                                    }
                                }
                            },
                            eventSources: [
                                           // your event source
                                               calendarJs._getCal()
                                           ]
                        
                        });
    });
</script>
